/* Shiro的配置类： yjj   */

package com.woniuxy.main.configuration;

import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.woniuxy.main.realm.UserRealm;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

@Configuration		//表示当前类为配置类：IOC容器会自动调用此类中的方法，创建对象
public class ShiroConfiguration {
	
	//realm
	@Bean		//<bean>
	public UserRealm createRealm(HashedCredentialsMatcher matcher) {
		UserRealm realm = new UserRealm();
		//realm.setCredentialsMatcher(matcher);
		return realm;
	}
	
	
	//安全管理器：方法如果有参数，IOC容器会自动注入对应的对象
	@Bean
	public DefaultWebSecurityManager createManager(UserRealm realm) {
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(realm);
		return manager;
	}
		
	//shiro过滤器
	@Bean
	public ShiroFilterFactoryBean createFilter(DefaultWebSecurityManager manager) {
		ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
		//设置安全管理器
		filter.setSecurityManager(manager);
		//请求其他页面跳转的页面
		filter.setLoginUrl("/chat/start");
		//没有权限时跳转的页面
		filter.setUnauthorizedUrl("/error.html");
		//过滤器链
		Map<String, String> map = new LinkedHashMap<String, String>();//有序的hashmap，保证过滤器链有序
		map.put("/chat/out", "logout");
		map.put("/chat/start", "anon");
		map.put("/chat/loadregister", "anon");
		map.put("/static/**", "anon");
		map.put("/js/**", "anon");
		map.put("/css/**", "anon");
		
//		map.put("/druid/**", "anon");//Druid
		map.put("/chat/**", "authc");
		filter.setFilterChainDefinitionMap(map);
		return filter;
	}
	
	
	/**
	 * 加密类型、次数
	 * @return
	 */
	@Bean
	public HashedCredentialsMatcher credentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
		matcher.setHashAlgorithmName("MD5");
		matcher.setHashIterations(1024);
		return matcher;
	}

	
	//创建在html中使用shiro标签时需要的对象,如果不创建html中shiro标签无法正常使用
	@Bean			
	public ShiroDialect dialect() {
		return new ShiroDialect();
	}
	
	
}
